<?php
declare(strict_types=1);

namespace app\shop\logic;

use app\shop\enums\coupon\CouponStatus;
use app\shop\model\user\UserCouponModel;
use think\Paginator;

class UserCouponLogic extends BaseLogic
{
    private UserCouponModel $model;

    public function __construct()
    {
        $this->model = new UserCouponModel();

        $this->checkExpiry();
    }

    /**
     * 列表
     * @param array $params
     * @return array|Paginator
     */
    public function list(array $params): Paginator|array
    {
        $couponStatus = $params['status'] ?? CouponStatus::TO_USE;

        $query = $this->model->getQuery();

        $query->with(['coupon']);

        $query->where([
            ['status', '=', $couponStatus]
        ]);

        $this->buildEqualQuery($query, $params, [
            'user_id' => 'user_id',
        ]);

        $query->order(['end_time' => 'asc']);

        $query->append(['disabled', 'used', 'expired', 'invalid']);

        return $this->model->paginateListQuery($query);
    }

    /**
     * 变更到期状态
     * @return void
     */
    private function checkExpiry(): void
    {
        $ids = $this->model->where([
            ['status', '=', CouponStatus::TO_USE],
            ['end_time', '<', time()]
        ])->column('id');

        if ($ids) {
            $this->model->whereIn('id', $ids)->update(['status' => CouponStatus::EXPIRED]);
        }
    }
}